using Domain.Entities;
using Domain.Entities.Enums;
using Domain.Services;
using System;
using UserInterface.Misc;

namespace UserInterface
{
    public partial class Login : BoardPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageTitle = (string)GetLocalResourceObject("Title");
            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.HeaderText = pageTitle;
            MasterPage.AddPathItem(pageTitle, "Login.aspx");
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            User user = UserService.GetByUsernameAndPassword(UsernameTextBox.Text, PasswordTextBox.Text);

            if (user != null)
            {
                if (user.Status == UserStatus.Activated || user.Status == UserStatus.RetrievingPassword)
                {
                    SessionManager.NewSession(user.Id);

                    if (user.Status == UserStatus.RetrievingPassword)
                    {
                        UserService.UpdateStatus(user, UserStatus.Activated);
                    }

                    Response.Redirect("Index.aspx");
                }
                else
                {
                    if (user.Status == UserStatus.AwaitingActivationByAdmin)
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("AdminActivationRequired"));
                    }
                    else if (user.Status == UserStatus.AwaitingActivationByEmail)
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("EmailActivationRequired"));
                    }
                    else if (user.Status == UserStatus.Disabled)
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("UserDisabled"));
                    }
                    else if (user.Status == UserStatus.DeniedByAdmin)
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("DeniedByAdmin"));
                    }
                    else if (user.Status == UserStatus.Reserved)
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("EmailActivationRequired"));
                    }
                }
            }
            else
            {
                MasterPage.Messages.AddCritical((string)GetLocalResourceObject("InvalidLogin"));
            }
        }
    }
}
